package menu

import (
	"context"
	"fast-boot/app/model"
	"github.com/jinzhu/copier"
	"strconv"

	"fast-boot/app/api/admin/internal/svc"
	"fast-boot/app/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 新增菜单
func NewAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLogic {
	return &AddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddLogic) Add(in *types.SysMenuForm) (resp *types.SysMenuFormResp, err error) {
	item := model.SysMenuModel{}
	if err := copier.Copy(&item, in); err != nil {
		return nil, err
	}

	treePath := "0"
	if in.ParentId > 0 {
		pTreePath := ""
		l.svcCtx.GormClient.GormDb.Model(model.SysMenuModel{}).Where("id = ?", in.ParentId).Pluck("tree_path", &pTreePath)
		treePath = pTreePath + "," + strconv.Itoa(int(in.ParentId))
	}
	item.TreePath = treePath

	l.svcCtx.GormClient.GormDb.Create(&item)
	return &types.SysMenuFormResp{
		Id: item.Id,
	}, nil
}
